<template>
  <div class="app-container">
    <list-page
      :total="total"
      v-model:page-num="searchForm.pageNum"
      v-model:page-size="searchForm.pageSize"
      @getList="getList">
      <template #search>
        <list-search v-model="searchForm" @search="search">
          <el-form-item label="角色名称" prop="like.name" class="w-220px">
            <el-input v-model="searchForm.like.name" placeholder="请输入角色名称" clearable @keyup.enter="search" />
          </el-form-item>
          <el-form-item label="权限字符" prop="like.role_key" class="w-220px">
            <el-input v-model="searchForm.like.role_key" placeholder="请输入权限字符" clearable @keyup.enter="search" />
          </el-form-item>
          <el-form-item label="状态" prop="where.status">
            <el-select v-model="searchForm.where.status" placeholder="角色状态" clearable class="w-120px">
              <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </list-search>
      </template>

      <template #actions>
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPerm="['system:role:add']">新增</el-button>
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="selections.length !== 1"
          @click="handleEdit"
          v-hasPerm="['system:role:edit']"
          >修改</el-button
        >
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="!selections.length"
          @click="handleDelete"
          v-hasPerm="['system:role:delete']"
          >删除</el-button
        >
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPerm="['system:role:export']"
          >导出</el-button
        >
      </template>

      <el-table v-loading="loading" :data="listData" @selection-change="handleSelection">
        <el-table-column type="selection" width="55" align="center" :selectable="canSelect" />
        <el-table-column label="编号" align="center" prop="id" width="60" />
        <el-table-column label="角色名称" align="center" prop="name" show-overflow-tooltip />
        <el-table-column label="权限字符" align="center" prop="role_key" show-overflow-tooltip />
        <el-table-column label="数据权限" align="center" show-overflow-tooltip>
          <template v-slot="{ row }">{{ dataScopeLabel(row.data_scope) }}</template>
        </el-table-column>
        <el-table-column label="显示顺序" align="center" prop="list_sort" />
        <el-table-column label="状态" align="center" width="80">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              active-value="1"
              inactive-value="0"
              @change="handleStatus(row)"
              v-if="statusPerm" />
            <dict-tag :options="sys_normal_disable" :value="row.status" v-else />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="create_time" width="140">
          <template #default="{ row }">{{ parseTime(row.create_time) }}</template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120" class-name="small-padding">
          <template #default="{ row }">
            <el-tooltip content="修改" placement="top" v-if="row.id !== rootRole">
              <el-button link type="primary" icon="Edit" @click="handleEdit(row)" v-hasPerm="['system:role:edit']" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top" v-if="row.id !== rootRole">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(row)"
                v-hasPerm="['system:role:delete']" />
            </el-tooltip>
            <el-tooltip content="数据权限" placement="top">
              <el-button
                link
                type="primary"
                icon="CircleCheck"
                @click="handleDataScope(row)"
                v-hasPerm="['system:role:data-scope']" />
            </el-tooltip>
            <el-tooltip content="分配用户" placement="top">
              <el-button
                link
                type="primary"
                icon="User"
                @click="handleAuthUser(row)"
                v-hasPerm="['system:role:auth-list']" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </list-page>

    <data-scope v-model="dataScopeShow" :id="dataScopeId" @submit="getList" v-if="dataScopeShow" />
    <role-form v-model="formShow" :row="formData" :module-name="moduleName" @submit="getList" v-if="formShow" />
  </div>
</template>

<script setup name="Role">
  import { listRoleApi, delRoleApi, changeStatusApi, exportRoleApi } from '@/api/system/role'
  import { useListPage } from '@/utils/hook/list-page'
  import { getDataScopeLabel } from './script'
  import RoleForm from './form.vue'
  import DataScope from './dataScope.vue'
  import { checkPerm } from '@/utils/auth'

  const router = useRouter()
  const { proxy } = getCurrentInstance()

  const {
    moduleName,
    searchForm,
    listData,
    loading,
    total,
    getList,
    search,
    selections,
    handleSelection,
    formData,
    formShow,
    handleAdd,
    handleEdit,
    handleDelete
  } = useListPage({ module: '角色', listFn, deleteFn })

  const statusPerm = computed(() => checkPerm('system:role:status'))
  const { sys_normal_disable } = proxy.useDict('sys_normal_disable')
  const rootRole = proxy.useInitLoad('root_role_id')

  onMounted(() => {
    getList()
  })

  // 查询角色列表
  function listFn() {
    loading.value = true
    listRoleApi(searchForm.value).then(res => {
      listData.value = res?.list || []
      total.value = res?.total || 0
      loading.value = false
    })
  }

  // 删除操作
  function deleteFn(params) {
    delRoleApi(params?.id || '').then(res => {
      proxy.$modal.msgSuccess(res?.msg || '删除成功')
      getList()
    })
  }

  //导出操作
  function handleExport() {
    exportRoleApi(searchForm.value)
  }

  // 角色状态修改
  function handleStatus(row) {
    let id = row?.id || undefined
    if (!id) return proxy.$modal.msgWarning('参数缺失')
    let text = row.status === '1' ? '启用' : '停用'
    proxy.$modal
      .confirm('确认要"' + text + '""' + row.name + '"角色吗?')
      .then(() => {
        return changeStatusApi(id, row.status)
      })
      .then(() => {
        proxy.$modal.msgSuccess(text + '成功')
      })
      .catch(function () {
        row.status = row.status === '0' ? '1' : '0'
      })
  }

  // 分配数据权限操作
  const dataScopeId = ref('')
  const dataScopeShow = ref(false)
  function handleDataScope(row) {
    dataScopeId.value = row?.id || ''
    if (!dataScopeId.value) return proxy.$modal.msgError('参数缺失')
    dataScopeShow.value = true
  }

  // 分配用户
  function handleAuthUser(row) {
    const roleId = row?.id || ''
    if (!roleId) return proxy.$modal.msgWarning('参数错误')
    router.push({ name: 'AuthUser', params: { roleId: roleId } })
  }

  // 数据权限展示
  function dataScopeLabel(value) {
    return getDataScopeLabel(value)
  }

  function canSelect(row) {
    return row.id !== rootRole.value
  }
</script>
